import { Module } from 'vuex'
import { GlobalDataProps, usersModuleTypeInterface } from '@/store/storeType'
import { getFn, putFn } from '../store_actions_axiosFn'
import { deleteFun, post, put } from '@/utils/axiosFunc'
import { arrToObj } from '@/utils/helper'


const usersModule: Module<usersModuleTypeInterface, GlobalDataProps> = {
  namespaced: true,
  state: () => ({
    usersData: {
      total: 0,
      pageNum: 1,
      users: {}
    },
    rolesData: {}
  }),
  mutations: {
    getUsersPageData (state, res) {
      if (res?.data?.meta?.status !== 200) return
      res.data.data.users = arrToObj(res.data.data.users)
      state.usersData = res.data.data
    },
    putUserData (state, res) {
      if (res.data.meta.status !== 200) return
      const { id } = res.data.data
      state.usersData.users[id] = res.data.data
    },
    getRolesData (state, res) {
      state.rolesData = arrToObj(res.data.data)
    }
  },
  actions: {
    getUsersPageData ({ commit }, pageParams) {
      return getFn('users', 'getUsersPageData', commit, pageParams)
    },
    postAddUsersData (context, addUserData = {}) {
      return post('users', addUserData)
    },
    putUserData ({ commit }, changeUsersDataAndUsersId) {
      return putFn(`users/${changeUsersDataAndUsersId.rowId}`, changeUsersDataAndUsersId.data, 'putUserData', commit)
    },
    async deleteUser (context, userId) {
      const res = await deleteFun(`users/${userId.rowId}`)
      return res
    },
    async putUsersState (context, userIdAndIsTrueData) {
      const { id, mg_state } = userIdAndIsTrueData
      const res = await put(`users/${id}/state/${mg_state}`)
      return res
    },
    getRolesData ({ commit }) {
      return getFn('roles', 'getRolesData', commit)
    },
    async updateRoles (context, ids) {
      const { id, rid } = ids
      const res = await put(`users/${id}/role`, { rid })
      return res
    }
  },
  getters: {
    usersFindData: (state) => (rowId: number) => {
      return state.usersData.users[rowId]
    }
  }
}

export default usersModule